package com.stropheware.droidDefense;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Vibrator;
import android.util.Log;

import com.stropheware.pathfinding.Path;

public class GameManager {
	
	public static final String TAG = "GameManager";
		
	public EnemyManager enemyManager;
	public TowerManager towerManager;
	public AchievementManager achievementManager;
	public GameBoard gameBoard;
	public GameThread gameThread;
	public Context context;
	public static final int MAX_LIVES = 10;
	public static final int STARTING_MONEY = 10000;
	private Vibrator vibrator = null;
	
	public static final int BASE_ENEMY_KILL_SCORE = 2;
	public static final int BASE_ROUND_COMPLETE_SCORE = 20;
	
	public long score = 0;
	public int roundNum = 0;
	public int money = STARTING_MONEY;
	public boolean isStoryMode = false;
	public boolean roundInProgress = false;
	public long livesLeft = MAX_LIVES;
	
	public static int tickCounter = 0; //realtime counter for game
			
	
	public GameManager(GameBoard gameBoard, GameThread gameThread, Context context) {
		this.gameThread = gameThread;
		this.context = context;
		this.gameBoard = gameBoard;
		this.achievementManager = new AchievementManager();
		enemyManager = new EnemyManager(this);
		towerManager = new TowerManager(this);
		vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
	}
	
	public synchronized void setRoundInProgress(boolean inProgress) {
		roundInProgress = inProgress;
	}
	
	public void lifeLost() {
		livesLeft--;
		vibrator.vibrate(300);
		if (livesLeft <= 0) {
			Log.d(TAG, "Game Over");
		}
	}
	
	
	public void startGame() {
		if(isStoryMode){
			Log.d(TAG, "showing first cutscene");
		}
	}
	
	public void updateGame() {
		tickCounter++;
		if(tickCounter == Integer.MAX_VALUE - 1) tickCounter = 0;
		if(roundInProgress) {
			enemyManager.update(tickCounter);
			towerManager.update(tickCounter);
		}
	}
	
	public void enemyKilled(AbstractEnemy enemy) {
		score += roundNum * BASE_ENEMY_KILL_SCORE;
		money += enemy.reward;
		achievementManager.notifyEnemyDestroy();
	}
	
	public void roundCompleted() {
		score += roundNum * BASE_ROUND_COMPLETE_SCORE;
		achievementManager.notifyRoundCompleted();
		setRoundInProgress(false);
	}
	
	public void drawGame(Canvas canvas) {
		towerManager.drawTowers(canvas);
		enemyManager.draw(canvas);
		towerManager.drawProjectiles(canvas);
	}
	
	public void startRound() {
		Log.d(TAG, ""+roundInProgress);
		if(!roundInProgress) {
			roundInProgress = true;
			enemyManager.startRound();
			roundNum++;
			Log.d(TAG, "round starting");
		}
	}
}
